package com.lizhaoshan.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Lu yuchao
 * @time 2022/5/10 0010 下午 8:53
 */

@Component
@Slf4j
@Data
public class OssTemplate {

    @Value("${reggie.oss.accessKey}")
    private String accessKeyId;

    @Value("${reggie.oss.secret}")
    private String accessKeySecret;

    @Value("${reggie.oss.bucketName}")
    private String bucketName;

    @Value("${reggie.oss.url}")
    private String url;

    @Value("${reggie.oss.endpoint}")
    private String endpoint;

    /**
     * 文件上传
     * @param suffixName
     * @param is
     * @return
     */
    public String upload(String suffixName, InputStream is) {
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + "." + suffixName;

       log.info("********文件名："+filename);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(bucketName, filename, is);

        ossClient.shutdown();

        String ossUrl = url + "/" + filename;

       log.info("*******url为:"+url);

        return ossUrl;
    }

}
